package cre.tomcat.ch05.core;

import org.apache.catalina.Container;
import org.apache.catalina.Mapper;
import org.apache.catalina.Request;
import org.apache.catalina.Wrapper;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author penglai
 * @Date 2017/1/27.
 */
public class SimpleContextMapper implements Mapper {

    private Container container;

    public Container getContainer() {
        return this.container;
    }

    public String getProtocol() {
        return null;
    }

    public Container map(Request request, boolean b) {
        String contextPath=((HttpServletRequest) request.getRequest()).getContextPath();
        String requestURI = ((HttpServletRequest) request).getRequestURI();

        String relativeURI = requestURI.substring(contextPath.length());
        String name = ((SimpleContext) container).findServletMapping(relativeURI);
        Wrapper wrapper = (Wrapper) ((SimpleContext) container).findChild(name);
        return wrapper;
    }

    public void setContainer(Container container) {
        if (container instanceof SimpleContext) {
            this.container = container;
        } else {
            throw new IllegalArgumentException("Illegal type of container");
        }
    }

    public void setProtocol(String s) {

    }
}
